﻿using Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace BGYMqttServer.HostedServices
{
    /// <summary>
    /// 历史版本临时目录清除后台服务
    /// </summary>
    class HistoryCleanBackgroundService : HostedBackgroundService
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly ILogger<HistoryCleanBackgroundService> logger;

        /// <summary>
        /// 历史版本临时目录清除后台服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="webHostEnvironment"></param>
        /// <param name="logger"></param>
        public HistoryCleanBackgroundService(
            IServiceProvider services,
            IWebHostEnvironment webHostEnvironment,
            ILogger<HistoryCleanBackgroundService> logger) : base(services)
        {
            this.webHostEnvironment = webHostEnvironment;
            this.logger = logger;
        }

        /// <summary>
        /// 删除app不用的临时目录
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Yield();

            var contentRoot = this.webHostEnvironment.ContentRootPath.TrimEnd('\\', '/');
            var baseDirectory = AppContext.BaseDirectory.TrimEnd('\\', '/');

            if (contentRoot.EqualsIgnoreCase(baseDirectory) == true)
            {
                return;
            }

            var appDirectory = Path.GetDirectoryName(baseDirectory);
            var appName = new DirectoryInfo(appDirectory).Name;
            if (appName.EqualsIgnoreCase(this.webHostEnvironment.ApplicationName) == false)
            {
                return;
            }

            var temDirName = new DirectoryInfo(baseDirectory).Name;
            foreach (var item in Directory.GetDirectories(appDirectory))
            {
                var curDir = new DirectoryInfo(item);
                if (temDirName.EqualsIgnoreCase(curDir.Name) == false)
                {
                    try
                    {
                        this.logger.LogInformation($"正在删除历史版本目录：{curDir.Name}");
                        curDir.Delete(recursive: true);
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogWarning(ex.Message);
                    }
                }
            }
        }
    }
}
